var express = require('express');
var request = require('request');
var fs = require('fs');
var multiparty = require('multiparty');
// 腾讯云的文件存储SDK
var CosSdk = require('cos-nodejs-sdk-v5');
var crypto = require('crypto');
var moment = require('moment');
var router = express.Router();
var config = require('../config');
var mysql = require('../util').mysql;
var corList = 'follow_community';
var qcloudConfig = JSON.parse(fs.readFileSync('/data/release/sdk.config.json', 'utf8'));
var cos = new CosSdk({
  AppId: qcloudConfig.qcloudAppId,
  SecretId: qcloudConfig.qcloudSecretId,
  SecretKey: qcloudConfig.qcloudSecretKey
});

router.get('/', function (req, res, next) {
  var open_id = req.query.open_id;
  var corInfo = [];
  var corPromise = [];
  var schPromise = [];
  var prePromise = [];
  var posPromise = [];
  var posNamPromise = [];
  mysql(corList)
    .where({ open_id: open_id })
    .select('*').then(function (ret) {
      var community_id = [];
      var i;
      var j = ret.length;
      for (i = 0; i < j; i++) {
        community_id[i] = ret[i].community_id;
        corInfo[i] = {
          community_avatar: null,
          community_id: ret[i].community_id,
          community_name: null,
          sch_id: null,
          sch_name: null,  //查学校表
          pre_name: null,  //查个人信息
          user_pos: null,  //查职位表
          tag_1: null,
          tag_2: null,
          tag_3: null,
          tag_4: null,
          tag_5: null,
          tag_6: null,
        };
      }
      for (i = 0; i < j; i++) {
        corPromise.push(
          mysql('community_info')
            .where({ community_id: community_id[i] })
            .select('*')
        )
      }
      Promise.all(corPromise).then(r => {
        console.log(r);
        var preId = [];
        var schId = [];
        for (i = 0; i < j; i++) {
          preId[i] = r[i][0].president_open_id;
          schId[i] = r[i][0].sch_id;
          corInfo[i].sch_id = r[i][0].sch_id;
          corInfo[i].community_name = r[i][0].community_name;
          corInfo[i].community_avatar = r[i][0].community_avatar;
        }
        for (i = 0; i < j; i++) {
          schPromise.push(
            mysql('school_direction')
              .where({ sch_id: schId[i] })
              .select('*')
          );
          prePromise.push(
            mysql('user_info')
              .where({ open_id: preId[i] })
              .select('*')
          );
          posPromise.push(
            mysql('community_manager')
              .where({
                open_id: open_id,
                community_id: community_id[i]
              })
              .select('*')
          );
        }
        Promise.all(schPromise).then(result => {
          for (i = 0; i < j; i++) {
            corInfo[i].sch_name = result[i][0].sch_name;
          }
        });
        Promise.all(prePromise).then(result => {
          for (i = 0; i < j; i++) {
            corInfo[i].pre_name = result[i][0].user_name;
          }
        });
        Promise.all(posPromise).then(result => {
          console.log(result);
          for (i = 0; i < j; i++) {
            if (result[i].length == 0) {
              continue;
            }
            else if (open_id == preId[i]) {
              corInfo[i].user_pos = '会长';
              continue;
            }
            else {
              corInfo[i].user_pos = result[i][0].position;
              continue;
            }
          }
          console.log(corInfo);
          res.json(corInfo);
        });
      })
    });
});
router.get('/allCorAdmin',function(req,res,next){
  mysql('community_manager').where(req.query).select('*')
    .then(function(ret){
      res.json(ret);
    })
});
//返回 活动分类、社团管理员列表 
router.get('/infoList', function (req, res, next) {
  var i;
  var community_id = req.query.community_id;
  var classPro = [];
  var managerPro = [];
  var managerItemPro = [];
  var infoList = {
    manager: [],
    classific: [],
  };
  managerPro.push(
    mysql('community_manager')
      .where({ community_id: community_id }).select('*')
  );
  Promise.all(managerPro).then(result => {
    console.log(result[0].length);
    for (i = 0; i < result[0].length; i++) {
      var managerItem = {
        open_id: result[0][i].open_id,
        manager_name: null,
        position: result[0][i].position
      }
      console.log(managerItem);
      infoList.manager[i] = managerItem;
      managerItemPro.push(
        mysql('user_info').where({ open_id: result[0][i].open_id }).select('*')
      );
    }
    Promise.all(managerItemPro).then(r => {
      for (i = 0; i < r.length; i++) {
        infoList.manager[i].manager_name = r[i][0].user_name;
      }
      classPro.push(
        mysql('activity_classification').select('*')
      );
      Promise.all(classPro).then(result => {
        for (i = 0; i < result.length; i++) {
          infoList.classific[i] = result[i][0];
        }
        res.json(infoList);
      });
    });
  });
});

router.post('/uploadCover', function (req, res, next) {
  console.log(req);
  var form = new multiparty.Form({
    encoding: 'utf8',
    autoFiles: true,
    uploadDir: '/tmp'
  });
  form.parse(req, function (err, fields, files) {
    if (err) {
      next(err);
    }
    else {
      console.log(files);
      var file = files.cover[0];
      var fileExtension = file.path.split('.').pop();
      var fileKey = parseInt(Math.random() * 10000000) + '_' + (+new Date) + '.' + fileExtension;
      var params = {
        //todo
        Bucket: config.coverCos.fileBucket,
        //ap-guangzhou
        Region: config.coverCos.region,
        Key: fileKey,
        Body: fs.readFileSync(file.path),
        ContentLength: file.size
      };
      // 发送
      cos.putObject(params, function (err, data) {
        // 删除临时文件↓
        fs.unlink(file.path);
        if (err) {
          next(err);
          return;
        }
        res.end(data.Location);
      });
    }
  });
});
router.post('/uploadTheme', function (req, res, next) {
  var form = new multiparty.Form({
    encoding: 'utf8',
    autoFiles: true,
    uploadDir: '/tmp'
  });
  form.parse(req, function (err, fields, files) {
    if (err) {
      next(err);
    }
    else {
      var file = files.theme[0];
      var fileExtension = file.path.split('.').pop();
      var fileKey = parseInt(Math.random() * 10000000) + '_' + (+new Date) + '.' + fileExtension;
      var params = {
        //todo
        Bucket: config.themeCos.fileBucket,
        //ap-guangzhou
        Region: config.themeCos.region,
        Key: fileKey,
        Body: fs.readFileSync(file.path),
        ContentLength: file.size
      };
      // 发送
      cos.putObject(params, function (err, data) {
        // 删除临时文件↓
        fs.unlink(file.path);
        if (err) {
          next(err);
          return;
        }
        res.end(data.Location);
      });
    }
  });
});

router.post('/newAct', function (req, res, next) {
  console.log(req);
  var newActInfo = {
    activity_id: null,
    activity_name: req.body.activity_name,
    community_id: req.body.community_id,
    manager_open_id: req.body.manager_open_id,
    classification_id: req.body.classification_id,
    sta_id: 1,
    sch_id: req.body.sch_id,  //actList中有
    manager_qq: req.body.manager_qq,
    manager_tel: req.body.manager_tel,
    manager_email: req.body.manager_email,
    start_time: req.body.start_time,
    end_time: req.body.end_time,
    activity_place: req.body.activity_place,
    activity_range: req.body.activity_range,
    cover_url: req.body.coverUrl,
    theme_url: req.body.themeUrl,
    passage_url: req.body.passage_url,
    other_matter: req.body.other_matter,
    readNum: 0,
    appendix_url: req.body.appendix_url,
    activity_tag1: req.body.activity_tag1,
    activity_tag2: req.body.activity_tag2,
    activity_tag3: req.body.activity_tag3,
    activity_tag4: req.body.activity_tag4,
    activity_tag5: req.body.activity_tag5,
    activity_tag6: req.body.activity_tag6,
  }
  mysql('activity_info').select('activity_id')
    .then(function (ret) {
      console.log(ret);
      newActInfo.activity_id = ret.length + 1;
      mysql('activity_info').insert(newActInfo).then(ret => {
        res.json(ret);
      })
    })
});
router.get('/actList', function (req, res, next) {
  var community_id = req.query.community_id;
  console.log(req);
  mysql('activity_info').where({ community_id: community_id })
    .select('*').then(function (ret) {
      console.log(ret);
      res.json(ret);
    })
  //需要在前端通过发布状态值   自行判断发布状态
});
router.post('/updateAct', function (req, res, next) {
  var activity_id = req.body.activity_id;
  var actInfo = req.body;
  console.log(req);
  console.log(actInfo);
  mysql('activity_info').where({ activity_id: activity_id })
    .update(actInfo).then(ret => {
      console.log(ret);
    });
});
router.delete('/delAct', function (req, res, next) {
  var actId = req.body.activity_id;
  mysql('activity_info')
    .where({ activity_id: actId })
    .select('*').del().then(function (ret) {
      res.json(ret);
    })
});
router.get('/getSug', function (req, res, next) {

  var activity_id = req.query.activity_id;
  mysql('act_suggestion').where({ activity_id: activity_id })
    .select('*').then(function (ret) {
      res.json(ret);
    });
});
router.post('/newSug', function (req, res, next) {
  //console.log(req);
  var sugInfo = req.body;
  mysql('act_suggestion').insert(sugInfo)
    .then(function (ret) { console.log(ret) });
});
router.get('/getCorTag', function (req, res, next) {
  var community_id = req.query.community_id;
  mysql('community_info').where({ community_id: community_id })
    .select('*').then(function (ret) {
      console.log(ret);
      res.json(ret);
    });
});
router.post('/updateCorTag', function (req, res, next) {
  var community_id = req.body.community_id;
  var tagInfo = req.body;
  mysql('community_info').where({ community_id: community_id })
    .update(tagInfo).then(function (ret) { console.log(ret); });
});
router.get('/getAdminList', function (req, res, next) {
  var community_id = req.query.community_id;
  var promise = [];
  var result = [];
  var i;
  mysql('community_manager').where({ community_id: community_id })
    .select('*').then(function (ret) {
      for (i = 0; i < ret.length; i++) {
        var open_id = ret[i].open_id;
        result[i] = {
          open_id: open_id,
          adminName: null,
          position: ret[i].position
        }
        promise.push(
          mysql('user_info')
            .where({ open_id: open_id })
            .select('*')
        );
      }
      Promise.all(promise).then(r => {
        console.log(r);
        for (i = 0; i < r.length; i++) {
          result[i].adminName = r[i][0].user_name;
        }
        console.log(result);
        res.json(result);
      });
    });
});
router.post('/chgPos', function (req, res, next) {
  var chgInfo = req.body;
  mysql('community_manager')
    .where({ community_id: chgInfo.community_id, open_id: chgInfo.open_id })
    .update(chgInfo).then(function (ret) {
      console.log(ret);
    })
});
router.delete('/delAdmin', function (req, res, next) {
  var community_id = req.body.community_id;
  var open_id = req.body.open_id;
  mysql('community_manager')
    .where({ community_id: community_id, open_id: open_id })
    .select('*').del().then(function (ret) {
      res.json(ret);
    })
});
router.get('/getCorApp', function (req, res, next) {
  var sch_id = req.query.sch_id;
  var result = {
    corList: [],
    president: []
  }
  var i;
  var promise = [];
  mysql('community_app').where({ sch_id: sch_id })
    .select('*').then(function (ret) {
      console.log(ret);
      result.corList = ret;
      for (i = 0; i < ret.length; i++) {
        var open_id = ret[i].president_open_id;
        promise.push(
          mysql('user_info').where({ open_id: open_id }).select('*')
        )
      }
      Promise.all(promise).then(r => {
        for (i = 0; i < r.length; i++) {
          result.president[i] = r[i][0].user_name;
        }
        console.log(result);
        res.json(result);
      });
    });
});
router.get('/getMyCorApp', function (req, res, next) {
  var president_open_id = req.query.president_open_id;
  mysql('community_app').where({ president_open_id: president_open_id })
    .select('*').then(function (ret) {
      res.json(ret);
    });
});
router.post('/newCorApp', function (req, res, next) {
  var corInfo = req.body;
  mysql('community_app').insert(corInfo).then(function (ret) {
    console.log(ret);
    res.json(ret);
  });
});
router.post('/acCorApp', function (req, res, next) {
  //请求中别忘了 avatar 和 community_id(客户端中设为0)
  var corInfo = req.body;
  mysql('community_info').select('*').then(function (ret) {
    var community_id = ret.length + 1;
    corInfo.community_id = community_id;
    mysql('community_info').insert(corInfo).then(function (ret) {
      console.log(ret);
      res.json(ret);
    });
  });
});
router.delete('/rjCorApp', function (req, res, next) {
  var corInfo = req.body;
  mysql('community_app').where(corInfo).select('*').del()
    .then(function (ret) {
      console.log(ret);
      res.json(ret);
    })
});
router.delete('/delCor', function (req, res, next) {
  //这里还需要添加删除其他表相关数据的指令
  var community_id = req.body.community_id;
  mysql('community_info').where({ community_id: community_id }).select('*').del()
    .then(function (ret) {
      console.log(ret);
      res.json(ret);
    })
});
router.get('/getAdminApp', function (req, res, next) {
  var community_id = req.query.community_id;
  var result = {
    appList: [],
    name: []
  }
  var i;
  var promise = [];
  mysql('manager_app').where({ community_id: community_id })
    .select('*').then(function (ret) {
      result.appList = ret;
      for (i = 0; i < ret.length; i++) {
        var open_id = ret[i].open_id;
        promise.push(
          mysql('user_info').where({ open_id: open_id }).select('*')
        )
      }
      Promise.all(promise).then(r => {
        for (i = 0; i < r.length; i++) {
          result.name[i] = r[i][0].user_name;
        }
        console.log(result);
        res.json(result);
      });
    });
});
router.get('/getMyAdminApp', function (req, res, next) {
  var open_id = req.query.open_id;
  mysql('manager_app').where({ open_id: open_id })
    .select('*').then(function (ret) {
      res.json(ret);
    });
});
router.post('/newAdminApp', function (req, res, next) {
  var appInfo = {
    open_id: req.body.open_id,
    community_id: req.body.community_id,
    position: req.body.position,
    state:'审核中'
  };
  mysql('manager_app').insert(appInfo).then(function (ret) {
    console.log(ret);
    res.json(ret);
  });
});
router.post('/acAdminApp', function (req, res, next) {
  var appInfo = {
    open_id: req.body.open_id,
    community_id: req.body.community_id,
    position: req.body.position,
    state: '已通过'
  };
  mysql('manager_app').where(req.body).update(appInfo)
    .then(function (ret) {
      console.log(ret);
      res.json(ret);
    })
  mysql('community_manager')
    .where({
      open_id: req.body.open_id,
      community_id: req.body.community_id,
    }).select('*').del()
    .then(function (ret) {
    console.log(ret);
    res.json(ret);
  });
  mysql('community_manager').insert(req.body).then(function (ret) {
    console.log(ret);
    res.json(ret);
  });
});
router.post('/rjAdminApp', function (req, res, next) {
  var appInfo = {
    open_id: req.body.open_id,
    community_id: req.body.community_id,
    position: req.body.position,
    state:'未通过'
  };
  mysql('manager_app').where(req.body).update(appInfo)
    .then(function (ret) {
      console.log(ret);
      res.json(ret);
    })
});
module.exports = router;